<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'wh:rd01:rd01:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #rds01List>
        <BasicTable @register="registerRds01Table" @row-click="handleRds01RowClick">
          <template #summary>
            <TableSummary fixed>
              <TableSummaryRow>
                <TableSummaryCell :index="0" align="center"> 合计： </TableSummaryCell>
                <TableSummaryCell :index="1" :col-span="4"> </TableSummaryCell>
                <TableSummaryCell :index="5" align="center">
                  {{ iqty }}
                </TableSummaryCell>
                <TableSummaryCell :index="6" align="right">
                  {{ fweight }}
                </TableSummaryCell>
                <!-- <TableSummaryCell :index="7" :col-span="4"> </TableSummaryCell> -->
              </TableSummaryRow>
            </TableSummary>
          </template>
        </BasicTable>
        <a-button class="mt-2" @click="handleRds01Add" v-auth="'wh:rd01:rd01:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="flow_wh_rd01"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'wh:rd01:rd01:edit'"
        @validate="handleValidate"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
  <div>
    <ListSelect
      ref="listSelectRef"
      :selectList="selectListRef"
      selectType="basInvSelect"
      :checkbox="true"
      @select="handleSelect"
      v-show="false"
    />
  </div>
</template>
<script lang="ts" setup name="ViewsWhRd01Rd01Form">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Rdrecord01, rd01Save, rd01Form } from '/@/api/wms/rd/rd01/Rdrecord01';
  import { basWarehouseTreeData } from '/@/api/bas/house/basWarehouse';
  import { ListSelect } from '/@/components/ListSelect';
  import { basPositionTreeData } from '/@/api/bas/pos/basPosition';
  import { companyTreeData } from '/@/api/sys/company';
  import { BpmButton } from '/@/components/Bpm';
  import { TableSummary, TableSummaryCell, TableSummaryRow } from 'ant-design-vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wh.rd01.rd01');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<Rdrecord01>({} as Rdrecord01);
  const loadingRef = ref(false);
  const listSelectRef = ref<any>(null);
  const selectListRef = ref<any>([]);
  const whCode = ref<any>('');

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增采购入库') : t('编辑采购入库'),
  }));

  const iqty = computed(() => {
    let sumiqty = 0;
    for (const record of rds01Table.getDataSource()) {
      const {
        editValueRefs: { iqty },
      } = record;
      sumiqty += Number(iqty || 0);
    }
    return sumiqty.toFixed(2);
  });

  const fweight = computed(() => {
    let sumfweight = 0;
    for (const record of rds01Table.getDataSource()) {
      const { fweight } = record;
      sumfweight += Number(fweight || 0);
    }
    return sumfweight.toFixed(4);
  });

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('入库单号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('所属公司'),
      field: 'companyCode',
      fieldLabel: 'company.companyName',
      component: 'TreeSelect',
      componentProps: {
        api: companyTreeData,
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('供应商编码'),
      field: 'venCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      ifShow: false,
    },
    {
      label: t('供应商名称'),
      field: 'venName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      label: t('预计到达日期'),
      field: 'preArrDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      label: t('来源单号'),
      field: 'sourceCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('仓库'),
      field: 'whCode',
      fieldLabel: 'basWare.cwhname',
      component: 'TreeSelect',
      componentProps: {
        api: basWarehouseTreeData,
        allowClear: true,
        onChange: (value) => {
          whCode.value = value;
          setRds01Columns();
        },
      },
    },
    {
      label: t('部门名称'),
      field: 'officeName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('单据状态'),
      field: 'djStatus',
      component: 'Select',
      componentProps: {
        dictType: 'sys_status',
      },
      dynamicDisabled: true,
    },
    {
      label: t('外部系统单号'),
      field: 'extCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('外部系统结果'),
      field: 'extRs',
      component: 'Input',
      componentProps: {
        maxlength: 1000,
      },
    },
    {
      label: t('外部系统时间'),
      field: 'extDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm:ss',
        showTime: { format: 'HH:mm:ss' },
      },
    },
    {
      label: t('制单人名称'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('修改人名称'),
      field: 'updateByName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('采购入库明细'),
      field: 'rds01List',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rds01List',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  const [registerRds01Table, rds01Table] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleRds01Delete.bind(this, record),
          },
          auth: 'wh:rd01:rd01:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setRds01Columns(_res: Recordable) {
    rds01Table.setColumns([
      {
        title: t('来源单号'),
        dataIndex: 'sourceCode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('来源行ID'),
        dataIndex: 'sourceDid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('商品ID'),
        dataIndex: 'invId',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {},
        editRule: true,
        ifShow: false,
      },
      {
        title: t('商品编码'),
        dataIndex: 'basInv.viewCode',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {},
        editRule: true,
      },
      {
        title: t('商品名称'),
        dataIndex: 'basInv.invName',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {},
        editRule: true,
      },
      {
        title: t('单位'),
        dataIndex: 'basInv.funitname',
        width: 80,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {},
        editRule: true,
      },
      {
        title: t('商品重量'),
        dataIndex: 'basInv.weight',
        width: 80,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {},
        editRule: true,
        ifShow: false,
      },
      {
        title: t('货位名称'),
        dataIndex: 'posCode',
        dataLabel: 'basPosition.posName',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          api: basPositionTreeData,
          params: { whcode: whCode.value },
          allowClear: true,
          canSelectParent: false,
        },
        editRule: false,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: ({ record }) => {
          return {
            onChange: (value, label) => {
              let weight = Number(record.cfree2 || 0);
              let num = Number(value || 0);
              let fweight = (num * weight).toFixed(4);
              rds01Table.updateTableDataRecord(record.id, {
                ...record,
                fweight,
              });
            },
          };
        },
        editRule: (value, _record) => {
          return new Promise((resolve, reject) => {
            if (value == 0) return reject('数量不能为0');
            if (!value || value == '') return reject('请输入数量');
            return resolve(); // 验证成功
          });
        },
        // editRule: true,
      },
      {
        title: t('重量'),
        dataIndex: 'fweight',
        width: 80,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('形象刊'),
        dataIndex: 'cfree1',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('自由项2'),
        dataIndex: 'cfree2',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('自由项3'),
        dataIndex: 'cfree3',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('公司名称'),
        dataIndex: 'parent.company.companyName',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'InputTextArea',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
    ]);
  }

  async function setRds01TableData(_res: Recordable) {
    await setRds01Columns();
    rds01Table.setTableData(record.value.rds01List || []);
  }

  function handleRds01RowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleRds01Add() {
    selectListRef.value = [];
    listSelectRef.value.openSelectModal();
  }

  function handleRds01Delete(record: Recordable) {
    rds01Table.deleteTableDataRecord(record);
  }

  async function getRds01List() {
    let rds01ListValid = true;
    let rds01List: Recordable[] = [];
    for (const record of rds01Table.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        rds01ListValid = false;
      }
      rds01List.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of rds01Table.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      rds01List.push({
        ...record,
        status: '1',
      });
    }
    if (!rds01ListValid) {
      throw { errorFields: [{ name: ['rds01List'] }] };
    }
    return rds01List;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await rd01Form(data);
    record.value = (res.rdrecord01 || {}) as Rdrecord01;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setRds01TableData(res);
    updateSchema([
      {
        field: 'code',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  function handleSelect(selectData) {
    selectData.forEach((item, index) => {
      rds01Table.insertTableDataRecord({
        id: new Date().getTime() + index,
        isNewRecord: true,
        editable: true,
        invId: item.invCode,
        companyCode: item.companyCode,
        basInv: {
          viewCode: item.viewCode,
          invName: item.invName,
          funitname: item.funitname,
          // weight: item.weight,
        },
        cfree2: item.weight,
        parent: {
          company: {
            companyName: item.company.companyName,
          },
        },
        // 'parent.company.companyName': item.company.companyName,
      });
    });
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      const data = await validate(); // 接受 BpmButton 传递过来的表单数据
      console.log('data', data);
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      data.rds01List = await getRds01List();
      // console.log('submit', params, data, record);
      const res = await rd01Save(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
